import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/home.vue'
import About from '../views/about.vue'
import Doc from '../views/doc.vue'
import AdminEbook from '../views/admin/admin-ebook.vue'
import AdminUser from '../views/admin/admin-user.vue'
import AdminCategory from '../views/admin/admin-category.vue'
import AdminDoc from '../views/admin/admin-doc.vue'
import store from "@/store";
import { Tool } from "@/utils/tool";

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      key: '/',

    }
  },
  {
    path: '/doc',
    name: 'Doc',
    component: Doc,
    meta: {
      key: '/doc',
    }
  },
  {
    path: '/about',
    name: 'About',
    component: About,
    meta: {
      key: '/about',
    }
  },
  {
    path: '/admin/user',
    name: 'AdminUser',
    component: AdminUser,
    meta: {

      key: '/admin/user',
      loginRequire: true

    }

  },
  {
    path: '/admin/ebook',
    name: 'AdminEbook',
    component: AdminEbook,
    meta: {
      key: '/admin/ebook',
      loginRequire: true

    }
  },
  {
    path: '/admin/category',
    name: 'AdminCategory',
    component: AdminCategory,
    meta: {
      key: '/admin/category',
      loginRequire: true

    }

  },
  {
    path: '/admin/doc',
    name: 'AdminDoc',
    component: AdminDoc,
    meta: {
      key: '/admin/doc',
      loginRequire: true

    }

  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 在路由导航之后，将 meta 属性的值保存到本地存储
// 路由登录拦截
router.beforeEach((to, from, next) => {
  // 侧边栏切换
  if (!to.matched.some((item) => item.meta.loginRequire)) {
    // 在一开始进入拦截时获取 meta 的值，排除具有 loginRequire 属性的路由
    const meta = to.meta;
    localStorage.setItem('meta', JSON.stringify(meta));
  }
  // 要不要对meta.loginRequire属性做监控拦截
  if (to.matched.some(function (item) {
    console.log(item, "是否需要登录校验：", item.meta.loginRequire);
    return item.meta.loginRequire
  })) {
    // 从vuex中拿取登录信息
    const loginUser = store.state.user;
    if (Tool.isEmpty(loginUser)) {
      console.log("用户未登录！");
      next('/');
    } else {
      next();
    }
  } else {
    next();
  }
});


export default router
